package com.huawei.videoservice.utils;

import com.huawei.common.utils.ThreadLocalUtil;
import com.huawei.videoservice.config.MinioProperties;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


@Component
public class MinioUtils {
    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;

    public void makeBucket(String bucketName){
        try {
            boolean found;
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } else {
                System.out.println("Bucket "+bucketName+" already exists.");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public String upload(MultipartFile file){

        String originalFilename = file.getOriginalFilename();
        String[] user = ThreadLocalUtil.get();
        String contentType = file.getContentType();
        System.out.println("contentType:" + contentType);
        String objectName = contentType.split("/")[0];
        System.out.println("objectName:" + objectName);
        String bucketName = user[0];
        makeBucket(bucketName);

        try {
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(objectName + "/" + originalFilename).stream(
                                    file.getInputStream(), -1, 10485760).contentType(contentType)
                            .build());
            String url;
            url = minioProperties.getEndpoint() +"/"+bucketName+"/"+objectName + "/" + originalFilename;
            System.out.println("文件已存入url为:"+url);
            return url;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }




























}
